#define LOSS_RATE0 0

module BcastNullP {
	provides {
		interface Bcast;
	}
	uses {
		interface Timer<TMilli> as Timer;
		interface AMSend as SendBcastMsg;
		interface CC2420Packet;
	}
}
implementation {
	//TOS_Msg msg;
	message_t msg;
	
	uint32_t dt;
	uint8_t numSync;

	void sendSyncMsg() {
		BcastMsg *bmsg = (BcastMsg *)call SendBcastMsg.getPayload(&msg, sizeof(BcastMsg));		
		if (TOS_NODE_ID != 0) {
                  return;
                }
		call CC2420Packet.setPower(&msg , 31);
		bmsg->type = BMTYPE_SYNC;
                bmsg->id = TOS_NODE_ID;
		
		// currentTime = call Timer.getNow();
		// memcpy(bmsg->cnt, &currentTime, 4);
		
		if (call SendBcastMsg.send(0xffff, &msg, sizeof(BcastMsg)) != SUCCESS) {
		  // call CC2420Packet.setPower(&msg, power);
		  call Timer.startOneShot(200);
		}		  
	}
	
	command void Bcast.startSync() {
		// power = call CC2420Packet.getPower(&msg);
                numSync = 0;
		if (TOS_NODE_ID == 0) {
		  dt = call Timer.getNow(); 
		}
		// Bcast a sync message
		sendSyncMsg();
	}
	
		
	command void Bcast.startBcast() { }
		
	event void Timer.fired() {
		sendSyncMsg();
	}
	
	event void SendBcastMsg.sendDone(message_t *pmsg, error_t error) {
          if (TOS_NODE_ID == 0 && ++numSync <= 3) {
            sendSyncMsg();  
	  }
	}
		
	command void Bcast.setTime() { }
	
	command uint32_t Bcast.getTime() {
		uint32_t localtime = call Timer.getNow();
		return localtime - dt;
	}
	
	command void Bcast.setDecode(uint32_t decode) { }
	
	command uint8_t Bcast.getLoss() { }
	
	command void Bcast.stopBcast() { }

	command void Bcast.inc(uint8_t counter) { }
}
